﻿/// <reference path="../vsdoc/jquery-1.8.3-vsdoc.js" />

var doRemove = "Do you really want to remove this item?";

asyncHandlersForEach.push(AppendTableTemplates);
function AppendTableTemplates()
{
    $("TBODY.hidden[id]").prependTo('BODY');
};
$(document).ready(function ()
{
    $("BUTTON[name=AddNewCollItem]").live('click', function (e)
    {
        e.preventDefault();
        var prefix = $(this).data("prefix");
        if (prefix != null && prefix != "")
        {
            prefix = prefix + ".";
        }
        var templateId = $(this).data("templateid");

        var parent = $(this).parents("TR").first(); // source for ID
        var target = $(parent).parents("TBODY").first(); // destination for result
        var ids = $("INPUT[name='" + prefix + "ExistingIDs'],INPUT[name='" + prefix + "RemoveIDs']")
            .map(function ()
            {
                return parseInt($(this).attr("value")) || 0;
            })
            .get();
        var maxValue = Math.max.apply(Math, ids) + 1;

        var rowTemplate = $("#" + templateId);
        if (rowTemplate.length > 0)
        {
            var newRow = $("<TABLE>");
            $(newRow).bindTemplate(
            {
                source: { index: maxValue }
                , template: rowTemplate
            });
            ($("TR", newRow).appendTo(target.prev()));
        }
    });
});

$(document).ready(function ()
{
    $("TABLE A.doRemoveItem").live('click', AddRemoveCheck);
});
function AddRemoveCheck(e)
{
    var parent = $(this).parents("TR").first();
    var collItem = $("INPUT.CollectionItem", $(parent));

    if (collItem == null
        || collItem.attr("value") == null
        || collItem.attr("value") == "")
    {
        return false;
    }

    if (confirm(doRemove))
    {
        var name = collItem.attr("name").replace("Existing", "Remove");
        collItem.attr("name", name);
        parent.hide();
    }
}